package com.shop.servlet.main;

import com.alibaba.fastjson.JSON;
import com.shop.pajo.Book;
import com.shop.service.book.BookServiceImpl;
import com.shop.service.book.IBookService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class MainServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method != null && method.equals("query")){
            this.query(req,resp);
        }
        if(method != null && method.equals("queryData")) {
            this.queryData(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
    public void query(HttpServletRequest req, HttpServletResponse resp) {
        String item = req.getParameter("item");
        List<Book> bookList = null;
        IBookService bookService = new BookServiceImpl();
        PrintWriter writer = null;
        if(item.equals("all")){
            bookList = bookService.query(null,null);
        }else {
            bookList = bookService.queryByClass(item);
        }
        try {
            writer = resp.getWriter();
            String s = JSON.toJSONString(bookList);
            writer.print(s);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    public  void queryData(HttpServletRequest req, HttpServletResponse resp) {
        String item = req.getParameter("item");
        List<Book> bookList = null;
        IBookService bookService = new BookServiceImpl();
        PrintWriter writer = null;

        bookList = bookService.query(item, null);

        try {
            writer = resp.getWriter();
            String s = JSON.toJSONString(bookList);
            writer.print(s);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }
}
